import time
import datetime
import logging
import paho.mqtt.client as mqtt
from django.core.management.base import BaseCommand
from asset.models import Device



TOPIC = '$SYS/broker/log/M/subscribe'
ONLINE_TAG = 'zxonline '
OFFLINE_TAG = 'zxoffline '


def on_message(client, userdata, message):
    logging.warning("--------begin--------")
    logging.warning("主题:" + " 消息:" + str(message.payload.decode("utf-8")))
    msg = message.payload.decode('utf-8')
    if ONLINE_TAG in msg:
        logging.warning('检测设备上线 %s' % datetime.datetime.now())
        device_uuid = msg.split(ONLINE_TAG)[1]
        device = Device.objects.filter(device_uuid=device_uuid).first()
        if device:
            device.online = True
            device.save()
            logging.warning('更新设备在线状态 %s 上线' % device.name)
        else:
            logging.warning('未匹配设备uuid %s' % device_uuid)
        logging.warning("--------end--------")
    if OFFLINE_TAG in msg:
        logging.warning("--------begin--------")
        logging.warning('检测设备下线 %s' % datetime.datetime.now())
        device_uuid = msg.split(OFFLINE_TAG)[1]
        device = Device.objects.filter(device_uuid=device_uuid).first()
        if device:
            device.online = False
            device.save()
            logging.warning('更新设备在线状态 %s 下线' % device.name)
        else:
            logging.warning('未匹配设备uuid %s' % device_uuid)
        logging.warning("--------end--------")

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        logging.warning("Connected to MQTT Broker!")
    else:
        logging.warning("Failed to connect, return code %d\n", rc)


# 自定义类,异常重订阅
class ResubscribeClient(mqtt.Client):
    TOPIC = ''

    def reconnect(self):
        super(ResubscribeClient, self).reconnect()
        if self.TOPIC:
            logging.warning("消息重新订阅......")
            self.subscribe(TOPIC)


def get_ws_client():
    client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    client = ResubscribeClient(client_id=client_id, transport='websockets')
    client.on_message = on_message
    client.on_connect = on_connect
    client.connect(host='localhost', port=6883)
    return client


class Command(BaseCommand):
    help = 'Subscribe real-time device status for mqtt link'

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        client = get_ws_client()
        client.subscribe(TOPIC)
        client.TOPIC = '$SYS/broker/log/M/subscribe'
        client.loop_forever()


